//
//  ChooseLayer.cpp
//  Cupcake
//
//  Created by luotianqiang1 on 17/4/13.
//
//

#include "ChooseLayer.h"
#include "FoodData.h"
#include "particleLayer.h"
#include "CutFruitLayer.h"
#include "RewardManager.h"
IMPLEMENT_COCOS2DX_CLASS(ChooseLayer);
REGIST_SECENE(ChooseLayer)
bool ChooseLayer::init(){
    if(BaseDecorationLayer::init()) {
        lock_postion_type= LOCK_POSITION_TYPE::TYPE_CENTER;
        _operate = StudioLayer::create("ChooseLayer.csb");
        addChild(_operate);
        _prompt = _operate->getNodeByName<Sprite*>("finger");
        categoryNames = {"flavor"};
        _decoView = KDS::MyScollView::create(getContentSize().width, 528);
        _decoView->setDirection(cocos2d::extension::ScrollView::Direction::HORIZONTAL);
        _decoView->setPosition(320,520);
        _decoView->setSpace(50);
        _decoView->setClippingToBounds(false);
        _decoView->setMarginLeft(30);
        _decoView->setMarginRight(30);
        _operate->getNodeByName("optionlayer")->addChild(_decoView);
        
        auto allFlavor = FoodData::getAllFlavor();
        for(int i=0;i<allFlavor.size();i++){
            cupPath.push_back("PNG/1/"+allFlavor[i]+".png");
            titlePath.push_back("PNG/1/"+allFlavor[i]+"_.png");
        }
        return true;
    }
    return false;
}

void ChooseLayer::touchEnd(ui::Widget* widget){
    
}


void ChooseLayer::onEnterTransitionDidFinish(){
    BaseDecorationLayer::onEnterTransitionDidFinish();
    kRewardManager->removeRewardLoadingCall = [this](){
        if(tempIndex != -1&&!kRewardManager->isLocked(tempKey)){
            auto tempNode = _decoView->nodeCache.at(tempIndex)->getChildByName(_lockName);
            if(tempNode){
                tempNode->retain();
                tempNode->removeFromParent();
                auto pos = _decoView->getContainer()->getPosition();
                for(int i=0;i<categoryNames.size();i++){
                    if(categoryNames.at(i) == _currentcategory){
                        this->creatIcon(i);
                        _decoView->getContainer()->setPosition(pos);
                    }
                }
                _decoView->nodeCache.at(tempIndex)->addChild(tempNode);
                tempNode->release();
                tempNode->runAction(Sequence::create(FadeOut::create(0.5),RemoveSelf::create(), nullptr));
                ActionHelper::delayFunc(0.4, tempNode, [tempNode](){
                    if( tempNode->getParent()){
                        auto particle = ParticleSystemQuad::create("particles/decorateParticle.plist");
                        particle->setPosition(tempNode->getParent()->getContentSize()*.5);
                        tempNode->getParent()->addChild(particle,1);
                        particle->stopSystem();
                        
                        SoundPlayer::getInstance()->playEffect("sound/general/draw_success.mp3");
                        particle->resetSystem();
                    }
                });
            }
        }
        tempIndex = -1;
        tempKey = "";
    };
    
    _eventDispatcher->setEnabled(false);
    this->creatIcon(0);
    _decoView->getContainer()->setPositionX(0);
    auto btns = _decoView->nodeCache;
    ssize_t maxSize = 5;
    auto num = min(btns.size()-1,maxSize);
    for(int i = num;i>=0;i--){
        auto node = btns.at(i);
        auto ornPos = node->getPosition();
        node->setVisible(false);
        ActionHelper::delayFunc((num-i)*0.4, this, [=](){
            auto ensPos = Vec2(node->getParent()->convertToNodeSpace(getContentSize()*.5).x,node->getPosition().y);
            if(i <=0)
                ensPos = node->getPosition();
            auto startPos = node->getParent()->convertToNodeSpace(Vec2::ZERO);
            node->setPosition(startPos);
            node->setScale(0.8f);
            node->runAction(ScaleTo::create(0.65f, 1));
            node->runAction(Sequence::create(JumpTo::create(0.65f, ensPos, 300, 1),MoveTo::create(abs(ornPos.x-node->getPosition().x)*0.0007, ornPos),CallFunc::create([=](){
                if(i ==0){
                    _eventDispatcher->setEnabled(true);
                }
            }), nullptr));
            SoundPlayer::getInstance()->playEffect("sound/general/ingredients_fly_in.mp3");
            
            node->setVisible(true);
        });
        
    }
}

void ChooseLayer::freeClick(KDS::EventSprite*widget,size_t index,KDS::MyScollView*){
    _eventDispatcher->setEnabled(false);
    widget->setEnable(false);
    _operate->setIsChange(true);
    auto allNames = FoodData::getAllFlavor();
    SoundPlayer::getInstance()->playEffect("sound/choose.mp3");
    FoodData::setFlavor(allNames[index]);
    for(auto node:_decoView->nodeCache){
        if(node != widget) {
            node->setEnable(false);
            auto wordPos = node->convertToWorldSpace(node->getContentSize()*.5);
            if(wordPos.x<getContentSize().width*.5){
                ActionHelper::hide(node, ActionHelper::ShowDirection::show_from_left);
            }else
                ActionHelper::hide(node, ActionHelper::ShowDirection::show_from_right);
        }
    }
    widget->removeAllChildren();
  
    widget->runAction(Sequence::create(ScaleTo::create(0.9f, 1.25f),CallFunc::create([=](){
        this->addChild(particleLayer::create(),10);
    }),DelayTime::create(1.5),CallFunc::create([this](){
        _eventDispatcher->setEnabled(true);
        auto nextStep = dynamic_cast<BaseStepLayer*>( DynObject::createDynObject(FoodData::getChooseNext()));
        if(nextStep){
            auto scene = Scene::create();
            scene->addChild(nextStep);
            Director::getInstance()->replaceScene(TransitionPageTurn::create(1.2, scene, false));
        }
    }), nullptr));
    widget->runAction(JumpTo::create(0.9f, widget->getParent()->convertToNodeSpace( getContentSize()*.5f), 200, 1));
    
    
}

void ChooseLayer::creatIcon(size_t _index){
    BaseDecorationLayer::creatIcon(_index);
    for(int i=0;i<_decoView->nodeCache.size();i++){
        auto node = _decoView->nodeCache.at(i);
        auto title = Sprite::create(titlePath[i]);
        title->setPosition(node->getContentSize().width*.5,15);
        node->addChild(title);
    }
}

vector<string> ChooseLayer::getIconPath(const string& _currentcategory){
    return cupPath;
}